package cn.edu.scau.disk.interceptor;

import cn.edu.scau.disk.exception.CommonException;
import cn.edu.scau.disk.utils.RedisConstant;
import cn.edu.scau.disk.utils.RedisUtil;
import cn.edu.scau.disk.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        //System.out.println("in preHandle");
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            //System.out.println("in Token");
            if(annotation != null){
                //System.out.println("need token");
                final String token = req.getHeader("token");
                if(token!=null && redisUtil.get(RedisConstant.TOKEN+token) != null){
                    //System.out.println("has token:"+token);
                    return true;
                }else {
                   // System.out.println("has not token");
                    throw new CommonException("请先登陆");
                }
            }else{
               // System.out.println("no need token");
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /*private void respError(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("in err");
        try {
            req.getRequestDispatcher("/example/login").forward(req, resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/


}
